import { getUserInfo } from '@requests/user'
import Taro from '@tarojs/taro'
export default {
  namespaced: true,
  state: {
    userInfo: {},
    token: null
    // token: 'f06eb22e29f4f04d9d8d7e0293d0fe4d'
  },
  mutations: {
    setUserInfo(state, payload) {
      state.userInfo = payload
    },
    setToken(state, payload) {
      state.token = payload
    }
  },
  actions: {
    init(context) {
      if (!context.state.token) {
        let data = Taro.getStorageSync('token')
        if (data) {
          data = JSON.parse(data)
          if (data.expire > new Date().getTime()) {
            context.commit('setToken', data.token)
          }
        }
      }
      if (context.state.token && !Object.keys(context.state.userInfo).length) {
        getUserInfo().then(res => {
          let userInfo = {
            name: res.result.name,
            mobile: res.result.mobile,
            head_img: res.result.user_info.head_url,
            personal_auth_statu: res.result.personal_auth_statu,
            vip_level: res.result.members,
            enterprise_certification_status:
              res.result.enterprise_certification_status,
            user_id: res.result.ycs_user_id
          }
          context.commit('setUserInfo', userInfo)
        })
      }
    }
  }
}
